package org.dreamwork.jasmine2.web.controls.chart.format;

import org.dreamwork.jasmine2.util.StringConverter;
import org.dreamwork.jasmine2.web.controls.chart.ChartContext;
import org.dreamwork.peony.DataBinder;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2010-5-12
 * Time: 10:16:28
 */
public class PieDataFormat implements IChartDataFormat {
    public String format(List<?> data, ChartContext context) {
        StringBuilder builder = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?><pie>");
        String textField = (String) context.getParameter("textField");
        String valueField = (String) context.getParameter("valueField");
        String colorField = (String) context.getParameter("colorField");
        String url = (String) context.getParameter("url");
        List<String> urlParamN = new ArrayList<String> ();

        if (!StringConverter.isEmpty(url)) {
            while (url.contains("{")) {
                String s = url.substring(url.indexOf('{') + 1, url.indexOf('}'));
                url = url.replace("{" + s + "}", "%s");
                urlParamN.add(s);
            }
        }
        if (data != null) for (Object container : data) {
            String title = (String) DataBinder.eval(container, textField);
            Object value = DataBinder.eval(container, valueField);
            builder.append("<slice title=\"").append(title).append("\" alpha=\"90\"");
            if (!StringConverter.isEmpty(colorField)) {
                String color = (String) DataBinder.eval(container, colorField);
                if (color != null) builder.append(" color=\"").append(color).append("\"");
            }
            if (!StringConverter.isEmpty(url)) {
                Object[] urlParamV = new Object[urlParamN.size()];
                for (int i = 0; i < urlParamN.size(); i++) {
                    urlParamV[i] = DataBinder.eval(container, urlParamN.get(i));
                }
                builder.append(" url=\"").append(String.format(url, urlParamV)).append("\"");
            }
            builder.append(">");
            String number = value == null ? "0" : value.toString();
            builder.append(number).append("</slice>");
        }
        builder.append("</pie>");
        return builder.toString();
    }
}